package com.niit.utils;

import java.util.Date;
import java.util.Enumeration;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;

public class WebKit {
	private static int LENGTH = 8;//随即产生用户名的长度
	public static  <T> T request2Bean(HttpServletRequest request,Class<T> clazz){
		
		try{
			T t = clazz.newInstance();
			ConvertUtils.register(new DateLocaleConverter(), Date.class);
			Enumeration<String> e = request.getParameterNames();
			while(e.hasMoreElements()){
				String name = e.nextElement();
				String value = request.getParameter(name);
				BeanUtils.setProperty(t, name, value);
			}
			return t;
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 产生用户名
	 */
	public static String getUsername(){
		
		String val = "";   
	    Random random = new Random();   
	    for(int i = 0; i < LENGTH; i++)   
	    {   
	        String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 输出字母还是数字   
	        if("char".equalsIgnoreCase(charOrNum)){ // 字符串   
	            int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; //取得大写字母还是小写字母   
	            val += (char) (choice + random.nextInt(26));   
	        }   
	        else if("num".equalsIgnoreCase(charOrNum)){ // 数字   
	            val += String.valueOf(random.nextInt(10));   
	        }   
	    }   
	    return val; 
	}
	
	/**
	 * 获取当前servlet的访问路径
	 */
	public static String getServletURI(HttpServletRequest request){
		return request.getContextPath()+request.getServletPath();
	}
	
	public static String getRandom(){
		String num = "";
		for(int i=0;i<6;i++){
			num+=Math.round(Math.random()*10)+"";
		}
		return num;
	}
	
}
